<?php

namespace Controller;

use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
use Symfony\Component\Validator\Constraints as Assert;

require_once ('../src/phpMailer/class.phpmailer.php');
use PHPMailer;

class DefaultCSP implements ControllerProviderInterface {
	public function connect(Application $app) {
		$controllers = $app ['controllers_factory'];
		$controllers->match ( '/', function (Application $app) {
			
			// Render
			return $app ['twig']->render ( "home.twig", array () );
		}, 'GET|POST' );
		
		$controllers->match ( '/{twig}', function (Application $app, $twig) {
			$content = array ();
			if ($twig == 'contact') {
				$form = $app ['form.factory']->createBuilder ( 'form' )->add ( 'name', 'text' )->add ( 'email', 'email' )->add ( 'phone', 'text', array (
						'required' => false 
				) )->add ( 'message', 'textarea' )->getForm ();
				$content ['form'] = $form->createView ();
			}
			
			// Render
			try {
				return $app ['twig']->render ( "$twig.twig", $content );
			} catch ( \Exception $ex ) {
				// your conditional code here.
				return $app ['twig']->render ( "404.twig", $content );
			}
		}, 'GET|POST' );
		
		$controllers->match ( '/Send/', function (Application $app) {
			$request = $app ['request'];
			$form = $app ['form.factory']->createBuilder ( 'form' )->add ( 'name', 'text' )->add ( 'email', 'email' )->add ( 'phone', 'text', array (
					'required' => false 
			) )->add ( 'message', 'textarea' )->getForm ();
			
			if ($request->getMethod () == 'POST') {
				$form->submit ( $request );
				$data = $form->getData ();
				$mailer = new PHPMailer ();
				$mailer->IsSMTP ();
				$mailer->Host = SMTP_HOST;
				$mailer->CharSet = "UTF-8";
				
				$mailer->SMTPAuth = true;
				$mailer->Username = SMTP_USER_ATDN;
				$mailer->Password = SMTP_PASS_ATDN;
				$mailer->From = $data ['email'];
				$mailer->FromName = $data ['name'];
				
				$mailer->Body = $app ['twig']->render ( "enquiry-template.twig", array (
						'name' => $data ['name'],
						'email' => $data ['email'],
						'phone' => $data ['phone'],
						'message' => $data ['message'] 
				) );
				$mailer->Subject = 'Enquiry';
				
				$mailer->isHTML ( true );
				$mailer->AddAddress ( 'luckyweida@gmail.com', 'Weida' );
				$mailer->Send ();
			}
			
			// Render
			return $app->redirect ( DOMAIN . '/contact' );
		}, 'GET|POST' );
		
		return $controllers;
	}
}